import Common from '@/utils/Common.js';
import request from '@/utils/request.js';
import service from '@/utils/request.js';
import {
	getUser,
	setUser,
	clearUser
} from '@/utils/auth';
import eventBus from '@/utils/eventBus.js';
import db from '@/utils/db';
import store from '@/store';

export default {
	data() {
		return {
			localUnprocessedCount: 0,
			localUnprocessedList: [],
			localProcessedCount: 0,
			localProcessedList: [],
			localCcCount: 0,
			localCcList: [],
			qualityUnprocessedCount: 0,
			qualityUnprocessedList: [],
			qualityProcessedCount: 0,
			qualityProcessedList: [],
			qualityCcCount: 0,
			qualityCcList: [],
			isProgressbar: true
		}
	},
	methods: {
		// 加载数据化在本地数据库进行同步
		storeTable: function (tableName, list) {
			let remoteMap = {};
			let localMap = {};
			let deleteCount = 0;
			let updateCount = 0;
			let insertCount = 0;
			for (let i = 0; i < list.length; i++) {
				let remote = list[i];
				remoteMap[remote.id] = remote;
			}
			var promise = Common.executeSql("select id, update_time from " + tableName, [])
				.then((result) => {
					let rs = result.rs;
					for (let i = 0; i < rs.rows.length; i++) {
						let local = rs.rows.item(i);
						localMap[local.id] = local;
					}
					let ids = [];
					for (let localId in localMap) {
						if (remoteMap[localId] == null) {
							ids.push(localId);
							delete localMap[localId];
						}
					}
					deleteCount = ids.length;
					return db.remove(tableName, ids);
				}).then(() => {
					console.log('syncTmp delete ' + tableName + ': ' + deleteCount);
					let elements = [];
					for (let localId in localMap) {
						let local = localMap[localId];
						let remote = remoteMap[localId];
						if (local.update_time != remote.updateTime) {
							elements.push(remote);
						}
					}
					updateCount = elements.length;
					return db.update(tableName, elements);
				}).then(() => {
					console.log('syncTmp update ' + tableName + ': ' + updateCount);
					let elements = [];
					for (var remoteId in remoteMap) {
						if (localMap[remoteId] == null) {
							let remote = remoteMap[remoteId];
							elements.push(remote);
						}
					}
					insertCount = elements.length;
					return db.insert(tableName, elements);
				}).then(() => {
					console.log('syncTmp insert ' + tableName + ': ' + insertCount);
					return Promise.resolve();
				}).catch(error => {
					console.error(error);
					return Promise.resolve();
				});
			return promise;
		},
		syncTmp: function (tableName, url, unprocessed) {
			var self = this;
			var list = [];
			var returnPromise = request({
				url: url,
				method: 'get',
				timeout: 60000 * 5,
				params: {
					userId: getUser().userId
				}
			}).then(data => {
				if (data.success) {
					list = data.list;
					self.storeTable(tableName, list);
				}
			}).then(() => {
				let promises = [];
				let promise = null;
				if (unprocessed == "现场检查") {
					promise = this.getRepairOrReinspect("/api/checkQualityRepair/findByProblemIds",
						"tb_checkquality_repair", list);
					promises.push(promise);
					promise = this.getRepairOrReinspect("/api/checkQualityReinspect/findByProblemIds",
						"tb_checkquality_reinspect", list);
					promises.push(promise);
				} /*else if (unprocessed == "实测实量") {
					promise = this.getRepairOrReinspect("/api/qualityMeasureCheckQualityRepair/findByProblemIds",
						"tb_quality_measure_checkquality_repair", list);
					promises.push(promise);
				}*/
				return  Promise.all(promises);
			}).catch(error => {
				console.error(error);
				return Promise.resolve();
			});
			return returnPromise;
		},
		getRepairOrReinspect: function (url, tableName, problems) {
			var self = this;
			let promise = null;
			var problemIds = [];
			//let formData = new FormData();
			for (var i = 0; i < problems.length; i++) {
				problemIds.push(problems[i].id);
				//formData.append("problemIds", problems[i].id);
			}
			if (problems.length > 0) {
				promise = request({
					url: url,
					method: 'get',
					timeout: 60000 * 5,
					params: {
						problemIds
					}
				}).then(data => {
					return self.storeTable(tableName, data.list);
				}).catch(error => {
					console.error(error);
					return Promise.resolve();
				});
			}
			return promise;
		},
		loadData: function () {
			var self = this;
			let promises = [];
			let startDate = self.$store.state.todo.startDate == null ? new Date().getTime() - 86400000*self.$store.state.todo.duration:
			self.$store.state.todo.startDate;
			let endDate =self.$store.state.todo.endDate == null ? new Date().getTime():self.$store.state.todo.endDate;
			var promise = this.syncTmp("tmp_unprocessed_problem_local_check_unprocessed",
				"/rest/unprocessed/localecheck/v3/findLocalCheckProblemByUser", "现场检查");
			promises.push(promise);
			promise = self.loadCcList("/rest/unprocessed/localecheck/v3/findLocalCheckCcProblemsByUser", {
				userId: getUser().userId,
				startDate: startDate,
				endDate: endDate
			},"现场检查");
			promises.push(promise);
			promise = this.syncTmp("tmp_unprocessed_problem_quality_measure_unprocessed",
				"/rest/unprocessed/qualitymeasure/v3/findQualityMeasureProblemsByUser", "实测实量");
			promises.push(promise);
			promise = self.loadCcList("/rest/unprocessed/qualitymeasure/v3/findQualityMeasureCcProblemsByUser", {
				userId: getUser().userId,
				startDate: startDate,
				endDate: endDate
			},"实测实量");
			promises.push(promise);

			var progress = 0;
			//var progressBarEl = self.$f7.progressbar.show("#demo-determinate-container", 0);
			var progressBarEl = self.$f7.progressbar.show(0, 'blue');
			promises.forEach(promise => {
				promise.then(() => {
					progress += 1;
					if (progress == promises.length) {
						self.$f7.progressbar.hide(progressBarEl)
					} else {
						self.$f7.progressbar.set(progressBarEl, 100 * progress / promises.length);
					}
				});
			});

			Promise.all(promises).then(function (values) {
				eventBus.$emit("load-count");
			});
		},
		loadCount: function () {
			let self = this;
			let startDate = self.$store.state.todo.startDate == null ? new Date().getTime() - 86400000*self.$store.state.todo.duration:
			self.$store.state.todo.startDate;
			let endDate =self.$store.state.todo.endDate == null ? new Date().getTime():self.$store.state.todo.endDate;
			let userId = getUser().userId;
			let localUnprocessedSql = "select count(*) as mount " +
				"from tmp_unprocessed_problem_local_check_unprocessed b " +
				"left join tb_checkquality_repair c on b.id = c.checkquality_problem_id " +
				"left join tb_checkquality_reinspect d on b.id = d.checkquality_problem_id " +
				"where c.child_checkquality_repair_id is null " +
				"and ((b.status = '待整改' and c.repair = '" + userId + "') " +
				"or (b.status = '待复验' and d.reinspect = '" + userId + "')) " +
				"GROUP BY b.id ";
			var promise = Common.executeSql(localUnprocessedSql, [])
				.then((result) => {
					self.localUnprocessedCount = result.rs.rows.length;
					console.log("load local unprocessed count: "+ result.rs.rows.length);
				});
			let localProcessedSql = "select count(*) as mount " +
			"from tmp_unprocessed_problem_local_check_unprocessed b " +
			"left join tb_checkquality_repair c on b.id = c.checkquality_problem_id " +
			"left join tb_checkquality_reinspect d on b.id = d.checkquality_problem_id " +
			"where c.child_checkquality_repair_id is null " +
			"and ((b.regist_by = '" + userId + "') " +
			"or ((b.status = '待复验' or b.status = '已通过') and b.repair_by = '" + userId + "') " +
			"or (b.status = '已通过' and b.reinspect_by = '" + userId + "')) " +
			"and b.update_time > " + startDate +
			" and b.update_time < " + endDate +
			" GROUP BY b.id ";
			var promise = Common.executeSql(localProcessedSql, [])
				.then(result => {
					self.localProcessedCount = result.rs.rows.length;
					console.log("load local processed count: "+ result.rs.rows.length);
				});

			let qualityUnprocessedSql = "select count(*) as mount " +
				"from tmp_unprocessed_problem_quality_measure_unprocessed b " +
				"left join tb_quality_measure_checkquality_repair c on b.id = c.quality_measure_checkquality_problem_id " +
				"where c.child_quality_measure_checkquality_repair_id is null " +
				"and ((b.status = '待整改' and c.repair = '" + userId + "') " +
				"or (b.status = '已整改' and b.regist_by = '" + userId + "')) ";
			var promise = Common.executeSql(qualityUnprocessedSql, [])
				.then(result => {
					self.qualityUnprocessedCount = result.rs.rows.item(0).mount;
					console.log("load quality unprocessed count: "+  result.rs.rows.item(0).mount);
				});

			let qualityProcessedSql = "select count(*) as mount " +
				"from tmp_unprocessed_problem_quality_measure_unprocessed b " +
				"left join tb_quality_measure_checkquality_repair c on b.id = c.quality_measure_checkquality_problem_id " +
				"where c.child_quality_measure_checkquality_repair_id is null " +
				"and ((b.status = '待整改' and b.regist_by = '" + userId + "') " +
				"or (b.status = '已整改' and b.repair_by = '" + userId + "') " +
				"or (b.status = '检查完毕' and b.regist_by = '" + userId + "')) " +
				"and b.update_time > " + startDate + " and b.update_time < " +
				endDate;
			var promise = Common.executeSql(qualityProcessedSql, [])
				.then(result => {
					self.qualityProcessedCount = result.rs.rows.item(0).mount;
					console.log("load quality processed count: "+  result.rs.rows.item(0).mount);
				});
		},
		loadLocalList: function (isChangeDate) {
			let self = this;
			let userId = getUser().userId;
			let startDate = self.$store.state.todo.startDate == null ? new Date().getTime() - 86400000*self.$store.state.todo.duration:
			self.$store.state.todo.startDate;
			let endDate =self.$store.state.todo.endDate == null ? new Date().getTime():self.$store.state.todo.endDate;
			if (!isChangeDate) {
				let localUnprocessedSql = "select b.*, c.id as checkquality_repair_id, c.repair, " + // id冲突
					"case when GROUP_CONCAT(distinct d.reinspect) is null then '[]' else '[' || GROUP_CONCAT(distinct '\"' || d.reinspect || '\"') || ']' end as reinspect, " +
					"case when GROUP_CONCAT(distinct d.reinspect) is null then '[]' else '[' || GROUP_CONCAT(distinct '\"' || d.id || '\"') || ']' end as checkquality_reinspect_id " +
					"from tmp_unprocessed_problem_local_check_unprocessed b " +
					"left join tb_checkquality_repair c on b.id = c.checkquality_problem_id " +
					"left join tb_checkquality_reinspect d on b.id = d.checkquality_problem_id " +
					"where c.child_checkquality_repair_id is null " +
					"and ((b.status = '待整改' and c.repair = '" + userId + "') " +
					"or (b.status = '待复验' and d.reinspect = '" + userId + "')) " +
					"GROUP BY b.id " +
					"order by b.regist_date desc";
				var promise = Common.executeSql(localUnprocessedSql, [])
					.then((result) => {
						self.localUnprocessedList = self.convertLocalProblem(result.rs.rows);
						console.log("load local unprocessed list: "+ result.rs.rows.length);
					});
			}
			let localProcessedSql = "select b.*, c.id as checkquality_repair_id, c.repair, " +
				"case when GROUP_CONCAT(distinct d.reinspect) is null then '[]' else '[' || GROUP_CONCAT(distinct '\"' || d.reinspect || '\"') || ']' end as reinspect, " +
				"case when GROUP_CONCAT(distinct d.reinspect) is null then '[]' else '[' || GROUP_CONCAT(distinct '\"' || d.id || '\"') || ']' end as checkquality_reinspect_id " +
				"from tmp_unprocessed_problem_local_check_unprocessed b " +
				"left join tb_checkquality_repair c on b.id = c.checkquality_problem_id " +
				"left join tb_checkquality_reinspect d on b.id = d.checkquality_problem_id " +
				"where c.child_checkquality_repair_id is null " +
				"and ((b.regist_by = '" + userId + "') " +
				"or ((b.status = '待复验' or b.status = '已通过') and b.repair_by = '" + userId + "') " +
				"or (b.status = '已通过' and b.reinspect_by = '" + userId + "')) " +
				"and b.update_time > " + startDate +
				" and b.update_time <" + endDate +
				" GROUP BY b.id " +
				"order by b.regist_date desc";
			var promise = Common.executeSql(localProcessedSql, [])
				.then(result => {
					self.localProcessedList = self.convertLocalProblem(result.rs.rows);
					console.log("load local processed list: "+ result.rs.rows.length);
				});
			self.loadCcList("/rest/unprocessed/localecheck/v3/findLocalCheckCcProblemsByUser", {
				userId: getUser().userId,
				startDate: startDate,
				endDate: endDate
			}, "现场检查");
		},
		loadQualityList: function (changeDate) {
			let self = this;
			let startDate = self.$store.state.todo.startDate == null ? new Date().getTime() - 86400000*self.$store.state.todo.duration:
			self.$store.state.todo.startDate;
			let endDate =self.$store.state.todo.endDate == null ? new Date().getTime():self.$store.state.todo.endDate;
			let userId = getUser().userId;
			if (!changeDate) {
				let qualityUnprocessedSql = "select b.*, c.repair " +
					"from tmp_unprocessed_problem_quality_measure_unprocessed b " +
					"left join tb_quality_measure_checkquality_repair c on b.id = c.quality_measure_checkquality_problem_id " +
					"where c.child_quality_measure_checkquality_repair_id is null " +
					"and ((b.status = '待整改' and c.repair = '" + userId + "') " +
					"or (b.status = '已整改' and b.regist_by = '" + userId + "')) " +
					"order by b.regist_date desc";
				var promise = Common.executeSql(qualityUnprocessedSql, [])
					.then((result) => {
						self.qualityUnprocessedList = self.convertQualityMeasureProblem(result.rs.rows);
						console.log("load quality unprocessed list: "+ result.rs.rows.length);
					});
			}
			let qualityProcessedSql = "select b.*, c.repair " +
				"from tmp_unprocessed_problem_quality_measure_unprocessed b " +
				"left join tb_quality_measure_checkquality_repair c on b.id = c.quality_measure_checkquality_problem_id " +
				"where c.child_quality_measure_checkquality_repair_id is null " +
				"and ((b.status = '待整改' and b.regist_by = '" + userId + "') " +
				"or (b.status = '已整改' and b.repair_by = '" + userId + "') " +
				"or (b.status = '检查完毕' and b.regist_by = '" + userId + "')) " +
				"and b.update_time > " + startDate + " and b.update_time < " +
				endDate +
				" order by b.regist_date desc";
			var promise = Common.executeSql(qualityProcessedSql, [])
				.then(result => {
					self.qualityProcessedList = self.convertQualityMeasureProblem(result.rs.rows);
					console.log("load quality processed list: "+ result.rs.rows.length);
				});
			self.loadCcList("/rest/unprocessed/qualitymeasure/v3/findQualityMeasureCcProblemsByUser", {
				userId: getUser().userId,
				startDate: startDate,
				endDate: endDate
			}, "实测实量");
		},
		loadList: function (sql, list, isLocal) {
			var promise = Common.executeSql(sql, [])
				.then(result => {
					if (isLocal) {
						list = self.convertLocalProblem(result.rs.rows);
					} else {
						list = self.convertQualityMeasureProblem(result.rs.rows);
					}
				});
			return promise;
		},
		loadCcList: function (url, params, unprocessed) {
			var self = this;
			var promise = request({
				url: url,
				method: 'get',
				timeout: 60000 * 5,
				params: params
			}).then(data => {
				if (data.success) {
					var problemList = self.convertCCProblem(data.element.ccProblem);
					if(unprocessed == "现场检查"){
						self.localCcList = problemList;
						self.localCcCount = self.localCcList.length;
					}else if(unprocessed == "实测实量"){
						self.qualityCcList = problemList;
						self.qualityCcCount = self.qualityCcList.length;
					}
					console.log('store load list finish: ccProblemList , length: ' + problemList.length);
				}
			}).catch(error => {
				console.error(error);
				return Promise.resolve();
			});
			return promise;
		},
		convertCCProblem: function (problemList) {
			var ccProblemList = [];
			for (var i = 0; i < problemList.length; i++) {
				problemList[i].qualityMeasureCheckqualityProblemId = problemList[i].id;
				problemList[i].repair = problemList[i].repairId;
				problemList[i].reinspect = Common.strToJson(problemList[i].reinspectIds);
				problemList[i].registDate = new Date(problemList[i].registDate);
				problemList[i].repairDeadline = new Date(problemList[i].repairDeadline);
				problemList[i].reinspectCompletedDate = new Date(problemList[i].reinspectCompletedDate);
				problemList[i].repairDate = new Date(problemList[i].repairDate);
				problemList[i].closeDate = new Date(problemList[i].closeDate);
				problemList[i].sentBackDate = new Date(problemList[i].sentBackDate);
				problemList[i].problemClassId = problemList[i].itemId;
				problemList[i].problemId = problemList[i].descId;
				problemList[i].ccs = Common.strToJson(problemList[i].ccs);
				problemList[i].problemValues = Common.strToJson(problemList[i].problemValues);
				problemList[i].reinspectImageFile = Common.strToJson(problemList[i].reinspectImageFile);
				problemList[i].repairImageFile = Common.strToJson(problemList[i].repairImageFile);
				problemList[i].imageFile = Common.strToJson(problemList[i].imageFile);
				problemList[i].smallImageFile = Common.strToJson(problemList[i].smallImageFile);
				problemList[i].sentBackImageFile = Common.strToJson(problemList[i].sentBackImageFile);
				ccProblemList.push(problemList[i]);
			}
			return ccProblemList;
		},
		convertLocalProblem: function (problemList) {
			var list = [];
			for (var i = 0; i < problemList.length; i++) {
				var row = problemList.item(i);
				var problem = {};
				problem.tid = row.tid;
				problem.batchId = row.batch_id;
				problem.bidSectionId = row.bid_section_id;
				problem.buildingId = row.building_id;
				problem.id = row.id;
				problem.contractorId = row.contractor_id;
				problem.itemId = row.item_id;
				problem.place = row.place;
				problem.problemValues = Common.strToJson(row.problem_values);
				problem.registBy = row.regist_by;
				problem.registDate = new Date(row.regist_date);
				problem.remark = row.remark;
				problem.repairDeadline = new Date(row.repair_deadline);
				problem.reinspectBy = row.reinspect_by;
				problem.reinspectCompletedDate = new Date(row.reinspect_completed_date);
				problem.reinspectImageFile = Common.strToJson(row.reinspect_image_file);
				problem.reinspectRemark = row.reinspect_remark;
				problem.repairBy = row.repair_by;
				problem.repairDate = new Date(row.repair_date);
				problem.repairImageFile = Common.strToJson(row.repair_image_file);
				problem.repairRemark = row.repair_remark;
				problem.problemClassId = row.item_id;
				problem.problemId = row.desc_id;
				problem.status = row.status;
				problem.imageFile = Common.strToJson(row.image_file);
				problem.smallImageFile = Common.strToJson(row.small_image_file);
				problem.roomId = row.room_id;
				problem.ccs = Common.strToJson(row.ccs);
				problem.closeDate = new Date(row.close_date);
				problem.closeReason = row.close_reason;
				problem.sentBackBy = row.sent_back_by;
				problem.sentBackDate = new Date(row.sent_back_date);
				problem.sentBackImageFile = Common.strToJson(row.sent_back_image_file);
				problem.sentBackRemark = row.sent_back_remark;
				problem.checkqualityRepairId = row.checkquality_repair_id;
				problem.repair = row.repair;
				problem.reinspect = Common.strToJson(row.reinspect);
				problem.checkqualityReinspectId = Common.strToJson(row.checkquality_reinspect_id);
				problem.houseTypeId = row.house_type_id;
				list.push(problem);
			}
			return list;
		},
		convertQualityMeasureProblem: function (problemList) {
			var list = [];
			for (var i = 0; i < problemList.length; i++) {
				var row = problemList.item(i);
				var problem = {};
				problem.appPermission = row.app_permission;
				problem.batchType = row.batch_type;
				problem.buildingId = row.building_id;
				problem.buildingName = row.building_name;
				problem.ccs = Common.strToJson(row.ccs);
				problem.drawingFile = Common.strToJson(row.drawing_file);
				problem.floorId = row.floor_id;
				problem.floorName = row.floor_name;
				problem.imageFile = Common.strToJson(row.image_file);
				problem.problemClassId = row.item_id;
				problem.measurePoints = row.measure_points;
				problem.problemPoints = row.problem_points;
				problem.problemValues = Common.strToJson(row.problem_values);
				problem.qualityMeasureCheckqualityProblemId = row.id;
				problem.registBy = row.regist_by;
				problem.registDate = new Date(row.regist_date);
				problem.remark = row.remark;
				problem.repairBy = row.repair_by;
				problem.repairDate = new Date(row.repair_date);
				problem.repairImageFile = Common.strToJson(row.repair_image_file);
				problem.repairRemark = row.repair_remark;
				problem.roomId = row.room_id;
				problem.roomName = row.room_name;
				problem.sentBackDate = new Date(row.sent_back_date);
				problem.sentBackImageFile = Common.strToJson(row.sent_back_image_file);
				problem.sentBackRemark = row.sent_back_remark;
				problem.sentBackTimes = row.sent_back_times;
				problem.smallImageFile = Common.strToJson(row.small_image_file);
				problem.smallRepairImageFile = Common.strToJson(row.small_repair_image_file);
				problem.smallSentBackImageFile = Common.strToJson(row.small_sent_back_image_file);
				problem.standardMax = row.standard_max;
				problem.standardMin = row.standard_min;
				problem.status = row.status;
				problem.tid = row.tid;
				problem.unitId = row.unit_id;
				problem.unitName = row.unit_name;
				problem.updateTime = new Date(row.update_time);
				problem.repair = row.repair;
				problem.bidSectionId = row.bid_section_id;
				list.push(problem);
			}
			return list;
		}
	},
	mounted: function () {
		var self = this;
		eventBus.$on("change-date", (params) => {
			self.loadLocalList(params);
			self.loadQualityList(params);
		});
		eventBus.$on("load-local-list", (params) => {
			self.loadLocalList(params);
		});
		eventBus.$on("load-quality-list", (params) => {
			self.loadQualityList(params);
		});
	},
	beforeDestroy () {
		eventBus.$off('change-date',this.handle);
		eventBus.$off('load-local-list',this.handle);
		eventBus.$off('load-quality-list',this.handle);
	},
}
